using System;
using Microsoft.SPOT;
using WebServer;
using System.Net;
using System.Net.Sockets;
using System.Threading;
using Microsoft.SPOT.Hardware;
using SecretLabs.NETMF.Hardware;
using SecretLabs.NETMF.Hardware.NetduinoPlus;
using System.Text;
using System.Text.RegularExpressions;
using System.Collections;
//using NetMf.CommonExtensions;
using SDCard;

public class UploadForm //  /Upload
    {
        public string DoUploadForm(BaseRequest request, SDCard.SDCard sdCard)
        {



            string line6 = @"<form method=""POST"" enctype=""multipart/form-data"" action=""/UploadForm"">
variable1: <input type=""text"" name=""variable1""><br>
path: <input type=""text"" name=""path""><br>
<br>
<input type=submit value=Press> to upload the form.
</form>";

            string line7 = "";
            string line8 = "";
            Hashtable formVariables = new Hashtable();
            if (request.HttpRequestType == EnumRequestType.Post)
            {
                PostRequest postRequest = (PostRequest)request;//same object just to save casting everywhere.
                // This form should be short so get it all data now, in one go.
                // assume no content sent with first packet todo fix
                int contentLengthFromHeader = int.Parse(postRequest.HeaderFields["Content-Length"].ToString());
                int contentLengthReceived = 0;
                string requestContent = "";
                while (contentLengthReceived < contentLengthFromHeader)// todo put timeout
                {
                    int count = 0;
                    byte[] data = postRequest.GetMoreBytesHandler(postRequest.ConnectionSocket, out count);
                    contentLengthReceived += count;
                    requestContent += new string(Encoding.UTF8.GetChars(data));

                }
                string boundary = postRequest.HeaderFields["boundary"].ToString(); 
//                int nextBoundaryIndex = requestContent.IndexOf(boundary);// todo boundaries can change
                string boundaryPattern = "--" + boundary;//"#\n\n(.*)\n--$boundary#"
                Regex MyRegex = new Regex(boundaryPattern, RegexOptions.Multiline);
//                string[] matches = MyRegex.GetMatches(requestContent);
                string[] split = MyRegex.Split(requestContent);
                ConsoleWrite.Print(MyRegex.ToString());
                for (int i = 0; i < split.Length; i++)
                {
                    Regex nameValuePairRegEx = new Regex("\r\n", RegexOptions.Multiline);
                    string[] nameValuePairSplit = nameValuePairRegEx.Split(split[i]);
                    if (nameValuePairSplit.Length >= 4)
                    {
                        string key = nameValuePairSplit[1].Substring(1,nameValuePairSplit[1].Length-2);// todo please refactor using regex properly and in safer manner
                        formVariables.Add(key, nameValuePairSplit[3]);
                    }
                }
            }
            foreach(string key in formVariables.Keys)
            {
                UTF8Encoding val = new UTF8Encoding();
                line7 += "<p>" + key + ": " + formVariables[key].ToString() + "</p>";
            }
            
            string content = HtmlGeneral.HtmlStart + line6 + line7 + line8 + HtmlGeneral.HtmlEnd;
            string header = HttpGeneral.GetHttpHeader(content.Length, "text/html", 1);
            return header + content;
        }
    }
